<?php

namespace app\index\model;

use app\common\RedisDB;

class UserModel extends BaseModel
{
    const INFO_KEY = 'user:';
    const AUTH_KEY = 'auth';
    const USERNAME_KEY = 'username_index';
    const USERID_KEY = 'userid';

    private $uid	= null;
    private $userinfo = null;
    private $noticelist=null;

    public function __construct($uid = null, $load = false ,$data=null)
    {
        parent::__construct();
        $this->redis = RedisDB::factory('user');
        $this->uid=$uid;
        if($uid)
        {
            if(!$this->redis->exists(self::INFO_KEY.$uid))
                $this->uid=$uid;
            else if($load)
            {
                $this->uid=$data['openid'];
                    $this->save($data);
            }
        }
    }

    public function  getNoticeList()
    {
        if($this->noticelist==null)
        {
            $notice=new NoticeModel($this);
        }
        return $this->noticelist;
    }

    public function getUid()
    {
        return $this->uid;
    }

    public function getInfo()
    {
        if($this->userinfo === null){
            $this->userinfo = $this->redis->hGetAll(self::INFO_KEY . $this->uid);
        }
        return $this->userinfo;
    }

    public function save($data)
    {
        $this->redis->hMSet(self::INFO_KEY . $this->uid, $data);
        $this->userinfo=null;
        $user=$this->getInfo();
        unset($user['lastlogintime']);
        unset($user['createtime']);
        unset($user['unusedtime']);
        DB('user')->update($user);
    }

    public function printinfo()
    {
        $user=$this->getInfo();
        print_r('uid:'.self::INFO_KEY . $this->uid);
        print_r($user);
    }

    private function incr($key, $value)
    {
        $this->redis->hIncrBy(self::INFO_KEY . $this->uid, $key, $value);
    }

    public function addDiamond($num)
    {
        $this->incr('diamond',$num);
        $this->userinfo=null;
        $user = $this->getInfo();
        db('user')->where("id='{$this->uid}'")->update(['diamond'=>$user['diamond']]);
    }

    public function login($uid, $token,$ip)
    {
        $val = $this->redis->hGet(self::AUTH_KEY, $uid);
        if($val != $token){
            //return false;
        }

        //remove auth info
        $this->redis->hDel(self::AUTH_KEY, $uid);
        //get userid
        $this->uid = $uid;
        if(!$this->uid){
            throw new Exception('UserNotExists');
        }
        $data['uid']=$uid;
        $data['logintime']=date("Y-m-d H:i:s",time());
        $data['loginip']=$ip;
        DB('loginlog')->insert($data);

        return true;
    }
}